package DataAccess;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import Domain.ShoppingCart;
import Domain.ShoppingCartItem;
import Exception.DadosException;

public class DAOShoppingCartItem extends DAOGenerico<ShoppingCartItem>
		implements IDAOShoppingCartItem {

	public DAOShoppingCartItem() {
		super();
		// TODO Auto-generated constructor stub
	}

	public List<ShoppingCartItem> consultarTodos() {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("Accenture");
		EntityManager entityManager = emf.createEntityManager();

		TypedQuery<ShoppingCartItem> tq = entityManager.createQuery(
				"SELECT aa FROM ShoppingCartItem aa", ShoppingCartItem.class);

		List<ShoppingCartItem> list = tq.getResultList();
		entityManager.close();
		emf.close();
		return list;

	}

	public ShoppingCartItem consultarPorIdNOVO(Integer id) {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("Accenture");
		EntityManager entityManager = emf.createEntityManager();

		ShoppingCartItem c = entityManager.find(ShoppingCartItem.class, id);

		entityManager.close();
		emf.close();
		return c;
	}

	public final void remover(ShoppingCartItem objeto) throws DadosException {

		EntityManagerFactory emf = Persistence.createEntityManagerFactory("Accenture");
		entityManager = emf.createEntityManager();

		EntityTransaction tx = entityManager.getTransaction();
		try {
			tx.begin();

			Query query = entityManager
					.createQuery("DELETE FROM ShoppingCartItem c WHERE c= :p");
			int deletedCount = query.setParameter("p", objeto).executeUpdate();

			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			throw new DadosException(DadosException.ERROR_DEL, e);
		}

		entityManager.close();
		emf.close();
	}

}
